/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ucjava.chat.socialnetworking.userinterface;

import com.ucjava.chat.commserve.rmi.common.User;
import com.ucjava.chat.socialnetworking.contacts.IContacts;
import com.ucjava.chat.socialnetworking.contacts.IMyFriends;
import com.ucjava.chat.socialnetworking.contacts.ISuggestedFriends;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;

/**
 *
 * @author adunagan
 */
public class AddFriendsUI extends javax.swing.JFrame {

    //private static final String HOST = "";
    //private static final int PORT = ;
    private static Registry registry;
    //create default list model for friends list
    DefaultListModel flModel = new DefaultListModel();
    //create default list model for friends you may know list
    DefaultListModel sfModel = new DefaultListModel();
    //create DefaultListModel for search results
    DefaultListModel resultsModel = new DefaultListModel();

    //work around class to get strings to display properly
    class DisplayableUser extends User {

        @Override
        public String toString() {
            return this.getUserName();
        }
    }

    /**
     * Creates new form AddFriendsUI
     */
    public AddFriendsUI() throws RemoteException, NotBoundException {
        initComponents();


        // RMI components to populate both friends lists and suggested friends lists with users from the server
        registry = LocateRegistry.getRegistry();
        IMyFriends fr = (IMyFriends) registry.lookup("MF");
        ArrayList<User> myFriends = fr.getMyFriendsList();
        ISuggestedFriends sf = (ISuggestedFriends) registry.lookup("SF");
        ArrayList<User> suggestedFriends = sf.getSuggestedFriends();


        // populates friends list with myFriends ArrayList
        //for each User in the friends ArrayList add it to the model
        for (int i = 0; i < myFriends.size(); i++) {
            //get user from array list
            User user = myFriends.get(i);
            //work around for getting proper string to display
            User dispUser = new DisplayableUser();
            dispUser.setUserName(user.getUserName());
            //add user to default list model
            myFriends.add(i, dispUser);
        }

        //add friends model to JList for friends
        listFriendsList.setModel(flModel);


        // populates "Friends You May know" with suggestedFriends ArrayList
        //for each User in the friends ArrayList add it to the model
        for (int i = 0; i < suggestedFriends.size(); i++) {
            //get user from array list
            User user = suggestedFriends.get(i);
            //work around for getting proper string to display
            User dispUser = new DisplayableUser();
            dispUser.setUserName(user.getUserName());
            //add user to default list model
            suggestedFriends.add(i, dispUser);
        }

        //add friends model to JList for friends
        listSuggested.setModel(sfModel);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lblAddFriendsTitle = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        txtSearch = new javax.swing.JTextField();
        btnSearch = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        listSearchResults = new javax.swing.JList();
        btnAllUsers = new javax.swing.JButton();
        jPanel4 = new javax.swing.JPanel();
        lblFriendsYouMayKnow = new javax.swing.JLabel();
        lblFriendsList = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        listSuggested = new javax.swing.JList();
        jScrollPane2 = new javax.swing.JScrollPane();
        listFriendsList = new javax.swing.JList();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        lblAddFriendsTitle.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        lblAddFriendsTitle.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lblAddFriendsTitle.setText("Add Friends");

        jPanel1.setLayout(new java.awt.GridLayout(0, 2));

        txtSearch.setText("Type a friend's name here.");
        txtSearch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtSearchActionPerformed(evt);
            }
        });
        jPanel1.add(txtSearch);

        btnSearch.setText("Search");
        btnSearch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSearchActionPerformed(evt);
            }
        });
        jPanel1.add(btnSearch);

        listSearchResults.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jScrollPane3.setViewportView(listSearchResults);

        jPanel1.add(jScrollPane3);

        btnAllUsers.setText("All Users");
        btnAllUsers.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAllUsersActionPerformed(evt);
            }
        });
        jPanel1.add(btnAllUsers);

        jPanel4.setLayout(new java.awt.GridLayout(0, 2));

        lblFriendsYouMayKnow.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        lblFriendsYouMayKnow.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lblFriendsYouMayKnow.setText("Friends you may know");
        jPanel4.add(lblFriendsYouMayKnow);

        lblFriendsList.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        lblFriendsList.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lblFriendsList.setText("Friends List");
        jPanel4.add(lblFriendsList);

        jPanel2.setLayout(new java.awt.GridLayout(0, 2));

        jScrollPane1.setViewportView(listSuggested);

        jPanel2.add(jScrollPane1);

        jScrollPane2.setViewportView(listFriendsList);

        jPanel2.add(jScrollPane2);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(lblAddFriendsTitle, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, 456, Short.MAX_VALUE)
            .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(lblAddFriendsTitle)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, 228, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnAllUsersActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAllUsersActionPerformed
        try {
            AllUsersUI all;
            all = new AllUsersUI();
            all.setVisible(true);
        } catch (RemoteException ex) {
            Logger.getLogger(AddFriendsUI.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NotBoundException ex) {
            Logger.getLogger(AddFriendsUI.class.getName()).log(Level.SEVERE, null, ex);
        }

    }//GEN-LAST:event_btnAllUsersActionPerformed

    private void txtSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtSearchActionPerformed
    }//GEN-LAST:event_txtSearchActionPerformed

    private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSearchActionPerformed
        try {
            // locate contacts on server and return an ArrayList named searchContacts
            registry = LocateRegistry.getRegistry();
            IContacts contacts = (IContacts) registry.lookup("AllContacts");
            ArrayList<User> searchContacts = contacts.getUserList();

            // creates an ArrayList to hold searchResults
            ArrayList<User> searchResults = new ArrayList<User>();

            // create user based on text box to be used to search against all users
            String strSearchUsers = txtSearch.getText();
            User searchUser = new User();
            searchUser.setUserName(strSearchUsers);


            //if search on contacts ArrayList contains user input add the user object to the search results ArrayList 
            if (searchContacts.contains(searchUser)) {
                searchResults.add(searchUser);

            } else {
                // display error if no matching user is found
                JOptionPane.showMessageDialog(null, strSearchUsers + " not found. Please try another name.");
            }

            // add user to results model
            for (int i = 0; i < searchResults.size(); i++) {
                //work around for getting proper string to display
                User dispUser = new DisplayableUser();
                dispUser.setUserName(searchUser.getUserName());
                //add user to default list model
                resultsModel.add(i, dispUser);
            }

            // add searchResults model to JList
            listSearchResults.setModel(resultsModel);

        } catch (RemoteException ex) {
            Logger.getLogger(AddFriendsUI.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NotBoundException ex) {
            Logger.getLogger(AddFriendsUI.class.getName()).log(Level.SEVERE, null, ex);

        }
    }//GEN-LAST:event_btnSearchActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(AddFriendsUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(AddFriendsUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(AddFriendsUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(AddFriendsUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    new AddFriendsUI().setVisible(true);
                } catch (RemoteException ex) {
                    Logger.getLogger(AddFriendsUI.class.getName()).log(Level.SEVERE, null, ex);
                } catch (NotBoundException ex) {
                    Logger.getLogger(AddFriendsUI.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAllUsers;
    private javax.swing.JButton btnSearch;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JLabel lblAddFriendsTitle;
    private javax.swing.JLabel lblFriendsList;
    private javax.swing.JLabel lblFriendsYouMayKnow;
    private javax.swing.JList listFriendsList;
    private javax.swing.JList listSearchResults;
    private javax.swing.JList listSuggested;
    private javax.swing.JTextField txtSearch;
    // End of variables declaration//GEN-END:variables
}
